package com.yc.sakuralxm.uestcscanning.tools

/**
 * Created by Administrator on 2016-10-18.
 */

import android.annotation.TargetApi
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Build
import android.os.Environment
import android.util.Log


import com.yc.sakuralxm.uestcscanning.AppContext

import org.json.JSONException
import org.json.JSONObject

import java.io.File
import java.io.FileOutputStream
import java.io.IOException

import okhttp3.Cache
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response

/**
 * 管理OKHttp 网络访问类
 * // "X-Access-Token", SharePrefUtils.getInstance().getSession()
 * Created by Jooyer on 2016/6/21
 *
 */
class OKhttpUtils {
    private val mOkHttpClient: OkHttpClient? = null

    private var mDataCallback: DataCallback? = null


    private object OnNewInstance {
        private val mFile = File(dirs)
        private val mCache = Cache(mFile, (10 * 1024 * 1024).toLong())
        public val INSTANCE = OkHttpClient.Builder().cache(mCache).build()
    }


    interface DataCallback {
        fun onFailure(call: Call, e: IOException)

        @Throws(JSONException::class)
        fun onSuccess(call: Call, json: String, obj: JSONObject)
        //
        //        void on603(JSONObject obj);

        @Throws(JSONException::class)
        fun onOther(obj: JSONObject)

        fun login(`object`: JSONObject, body: RequestBody)
        //        default void  login(JSONObject object){
        //
        //        }
    }

    fun setDataCallback(callback: DataCallback) {
        mDataCallback = callback
    }

    companion object {
        //头像保存目录名称
        var PHOTO_DIR = Environment.getExternalStorageDirectory().toString() + File.separator +
                "Model" + File.separator + "Photos"
        //缓存保存目录名称
        private val dirs = Environment.getExternalStorageDirectory().toString() + File.separator +
                "Model" + File.separator + "Cache"

        val okHttpClient: OkHttpClient
            get() = OnNewInstance.INSTANCE

        fun request(activity: Activity, request: Request?, callback: DataCallback?) {
            okHttpClient.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    Log.i("OKHttpUtils", "=====onFailure=======" + e.toString())
                    activity.runOnUiThread { callback!!.onFailure(call, e) }
                }

                @Throws(IOException::class)
                override fun onResponse(call: Call, response: Response) {
                    try {
                        val json = response.body().string()
                        L.e("OKHttpUtils" + json)
                        val `object` = JSONObject(json)
                        activity.runOnUiThread {
                            // 返回的东西根据具体而定 这个每次都要改 这次是 code = 200;
                            if (1 == `object`.optInt("code")) {
                                Log.i("OKHttpUtils", "=====1=======" + json)
                                try {
                                    callback?.onSuccess(call, json, `object`)
                                } catch (e: JSONException) {
                                    e.printStackTrace()
                                }

                            } else if (401 == `object`.optInt("code")) {
                                Log.i("OKHttpUtils", "=====other=======" + `object`.optString("message") + "=========" + `object`.optString("code"))
                                callback?.login(`object`, request!!.body())
                            } else {
                                Log.i("OKHttpUtils", "=====other=======" + `object`.optString("message") + "=========" + `object`.optString("code"))
                                if (callback != null)
                                    try {
                                        callback.onOther(`object`)
                                    } catch (e: JSONException) {
                                        e.printStackTrace()
                                    }

                            }
                        }
                    } catch (e: JSONException) {
                        L.e(response.toString())
                        e.printStackTrace()
                    }

                }
            })
        }

        fun request(activity: Activity, request: Request, dialog: Dialog?, callback: DataCallback?) {
            okHttpClient.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    Log.i("OKHttpUtils", "=====onFailure=======" + e.toString())
                    activity.runOnUiThread {
                        callback!!.onFailure(call, e)
                        dialog?.dismiss()
                    }

                }

                @Throws(IOException::class)
                override fun onResponse(call: Call, response: Response) {
                    try {
                        val json = response.body().string()
                        val `object` = JSONObject(json)
                        activity.runOnUiThread {
                            dialog?.dismiss()
                            // 返回的东西根据具体而定 这个每次都要改 这次是 code = 200;
                            if (1 == `object`.optInt("code")) {
                                Log.i("OKHttpUtils", "=====0=======" + json)
                                try {
                                    callback?.onSuccess(call, json, `object`)
                                } catch (e: JSONException) {
                                    e.printStackTrace()
                                }

                            } else if (401 == `object`.optInt("code")) {
                                Log.i("OKHttpUtils", "=====other=======" + `object`.optString("message") + "=========" + `object`.optString("code"))
                                callback?.login(`object`, request.body())
                            } else {
                                Log.i("OKHttpUtils", "=====other=======" + `object`.optString("message") + "=========" + `object`.toString())
                                if (callback != null)
                                    try {
                                        callback.onOther(`object`)
                                    } catch (e: JSONException) {
                                        e.printStackTrace()
                                    }

                            }
                        }
                    } catch (e: JSONException) {
                        activity.runOnUiThread {
                            dialog?.dismiss()
                        }
                        L.e(response.toString())
                        e.printStackTrace()
                    }

                }
            })
        }


        /**
         * get请求
         * @param activity
         * @param url
         * @param callback
         */
        operator fun get(activity: Activity, url: String, callback: DataCallback) {
            val request = Request.Builder().url(url).get().build()
            request(activity, request, callback)
        }

        fun post(activity: Activity, url: String, s: String, callback: DataCallback) {
            val request = Request.Builder().url(url).header("content-type", "application/json;charset=UTF-8")
                    .addHeader("token", AppContext.app.token).post(RequestBody.create(JSON, s)).build()
            request(activity, request, callback)
        }

        fun post(activity: Activity, url: String, s: String, dialog: Dialog, callback: DataCallback) {
            val request = Request.Builder().url(url).header("content-type", "application/json")
                    .header("Authorization", "CONTROLLER:{{ControllerAuthKey}}")
                    .post(RequestBody.create(JSON, s)).build()
            L.e(request.toString())
            request(activity, request, dialog, callback)
        }

        val JSON = MediaType.parse("application/json; charset=utf-8")
        fun put(activity: Activity, url: String, body: RequestBody, callback: DataCallback) {
            val request = Request.Builder().url(url).put(body).build()
            request(activity, request, callback)
        }

        fun delete(activity: Activity, url: String, body: RequestBody?, callback: DataCallback) {
            var request: Request? = null
            if (null == body) {
                request = Request.Builder().url(url)
                        .delete().build()
            } else {
                request = Request.Builder().url(url).delete(body).build()
            }
            request(activity, request, callback)
        }

        //    public void ConfigureTimeouts() throws Exception {
        //        mOkHttpClient = new OkHttpClient.Builder()
        //                .connectTimeout(10, TimeUnit.SECONDS)
        //                .writeTimeout(10, TimeUnit.SECONDS)
        //                .readTimeout(30, TimeUnit.SECONDS)
        //                .build();
        //    }


        //    File file = new File(FileUtils.SDPATH + "log.txt");
        //    try {
        //        FileOutputStream os = new FileOutputStream(file);
        //        os.write(json.getBytes());
        //        os.flush();
        //    } catch (IOException e) {
        //        e.printStackTrace();
        //    }

        @TargetApi(Build.VERSION_CODES.KITKAT)
        fun cachePhoto(context: Context, url: String, fileName: String) {
            val file = File(context.getExternalFilesDir(Environment.MEDIA_UNKNOWN), fileName + ".png")
            if (!android.text.TextUtils.isEmpty(url)) {
                val request = Request.Builder().url(url).get().build()
                OKhttpUtils.okHttpClient.newCall(request).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {}

                    @Throws(IOException::class)
                    override fun onResponse(call: Call, response: Response) {
                        val fos = FileOutputStream(file)
                        fos.write(response.body().bytes())
                        fos.flush()
                    }
                })
            }
        }
    }

}
